<!--
 * @Author: early-autumn
 * @Date: 2020-05-11 20:38:20
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-03 10:37:54
 -->
<template>
  <div class="app-container">
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      label-width="68px"
    >
      <el-row>
        <el-col>
          <el-form-item class="datetimerange">
            <el-button type="primary" size="medium" @click="prev"
              >&lt;</el-button
            >
            <el-date-picker
              v-model="dateTimeValue"
              type="date"
              :clearable="false"
              placeholder="选择日期"
              @change="onChange"
            ></el-date-picker>
            <el-button type="primary" size="medium" @click="next"
              >&gt;</el-button
            >
          </el-form-item>
          <el-form-item label="医生" prop="doctorId" class="datetimerange">
            <el-select
              v-model="queryParams.doctorId"
              filterable
              clearable
              placeholder="请选择医生"
              @change="selectDoctor"
            >
              <el-option
                v-for="item in doctorList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="datetimerange">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="small"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
              >重置</el-button
            >
            <el-button type="warning" icon="el-icon-full-screen" size="small"
              >导出</el-button
            >
            <columns-filter-button size="small" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      v-loading="loading"
      stripe
      border
      :data="list"
      :height="clientHeight"
      :max-height="clientHeight"
      @row-click="handleDetails"
      @cell-dblclick="doubleHandle"
    >
      <el-table-column
        fixed="left"
        width="70"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <el-radio v-model="radio" class="radio" :label="scope.$index"
            >&nbsp;</el-radio
          >
        </template>
      </el-table-column>

      <columns-filter-view>
        <el-table-column
          label="姓名"
          align="center"
          prop="yiyaClinicPerson.name"
        >
          <template slot-scope="scope">
            <div style="cursor: pointer">
              {{ scope.row.yiyaClinicPerson.name }}
            </div>
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="手机号"
          align="center"
          :min-width="'手机号码'.length * 40"
        >
          <template slot-scope="scope">
            <hover-phone :items="scope.row.yiyaClinicPerson" :type="1" />
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="性别"
          align="center"
          prop="yiyaClinicPerson.sex"
          :formatter="(_, __, value) => formatterDict(value, 'sexOptions')"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="年龄"
          align="center"
          prop="yiyaClinicPerson.age"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="到店时间"
          align="center"
          prop="yiyaAppointment.onClinicTime"
          :min-width="'到店状态'.length * 30"
        >
          <template slot-scope="scope">
            <span>
              {{
                parseTime(scope.row.yiyaAppointment.onClinicTime, '{h}:{i}:{s}')
              }}
            </span>
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="预约时间"
          align="center"
          prop="yiyaAppointment.startReservationTime"
          :min-width="'到店状态'.length * 30"
        >
          <template slot-scope="scope">
            <span>
              {{
                parseTime(
                  scope.row.yiyaAppointment.startReservationTime,
                  '{h}:{i}:{s}'
                )
              }}
            </span>
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="预约类型"
          align="center"
          prop="yiyaAppointment.onClinicTime"
          :min-width="'到店状态'.length * 30"
        >
          <template slot-scope="scope">
            <span>
              {{
                scope.row.yiyaAppointment.onClinicTime == '' ||
                scope.row.yiyaAppointment.onClinicTime == null
                  ? '预约'
                  : '到店'
              }}
            </span>
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="医生"
          align="center"
          min-width="100"
          prop="yiyaAppointment.doctorName"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="客户状态"
          align="center"
          prop="yiyaAppointment.personStatus"
          :min-width="'到店状态'.length * 30"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="看诊项目"
          align="center"
          prop="yiyaAppointment.reservationProject"
          :min-width="'到店状态'.length * 30"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="就诊状态"
          align="center"
          prop="yiyaAppointment.appointmentStatus"
          min-width="120"
          :formatter="
            (row, column, value) => {
              return value == 3
                ? `等待 ${parseInt(
                    (new Date() - row.yiyaAppointment.onClinicTimeDate) / 60000
                  )} 分钟`
                : formatterDict(value, 'attendanceStatus')
            }
          "
        />
      </columns-filter-view>

      <columns-filter-view>
        <el-table-column
          label="备注"
          align="center"
          :show-overflow-tooltip="true"
          prop="yiyaAppointment.remarks"
        />
      </columns-filter-view>

      <el-table-column label="接诊" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="
              scope.row.yiyaAppointment.appointmentStatus !== 5 &&
              scope.row.yiyaAppointment.appointmentStatus !== 4
            "
            size="mini"
            circle
            icon="el-icon-plus"
            @click="checkReception(scope.row.yiyaAppointment, '开始治疗')"
          ></el-button>
          <el-button
            v-else
            size="mini"
            disabled
            type="success"
            circle
            icon="el-icon-check"
          ></el-button>
        </template>
      </el-table-column>

      <el-table-column label="病历" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.yiyaAppointment.isCase == 0"
            size="mini"
            circle
            icon="el-icon-plus"
            @click="addCaseHandle(scope.row)"
          ></el-button>
          <el-button
            v-else
            size="mini"
            circle
            type="success"
            icon="el-icon-check"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column label="随访" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.yiyaAppointment.isVisit == 0"
            size="mini"
            circle
            icon="el-icon-plus"
            @click="handleIsVisit(scope.row)"
          ></el-button>
          <el-button
            v-else
            size="mini"
            circle
            type="success"
            icon="el-icon-check"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column label="复诊预约" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.yiyaAppointment.isAppointment == 0"
            size="mini"
            circle
            icon="el-icon-plus"
            @click="handleAgainAppointment(scope.row)"
          ></el-button>
          <el-button
            v-else
            size="mini"
            circle
            type="success"
            icon="el-icon-check"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column label="上传影像" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.yiyaAppointment.isShadow == 0"
            size="mini"
            circle
            icon="el-icon-plus"
            @click="addShadows(scope.row)"
          ></el-button>
          <el-button
            v-else
            size="mini"
            circle
            type="success"
            icon="el-icon-check"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column label="治疗完成" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.yiyaAppointment.appointmentStatus !== 5"
            size="mini"
            circle
            icon="el-icon-plus"
            @click="checkReception(scope.row.yiyaAppointment, '治疗完成')"
          ></el-button>
          <el-button
            v-else
            size="mini"
            circle
            type="success"
            disabled
            icon="el-icon-check"
          ></el-button>
        </template>
      </el-table-column>

      <template slot="empty">
        <empty></empty>
      </template>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <medical-editor
      v-model="medicalEditorVisible"
      :clinic-person-id="patientId"
      :title="titles"
      :user-person="caseYiyaClinicPerson"
      :user-appointment="caseYiyaAppointment"
      @close="changeHandle"
      @submit="addNewCase"
    />
    <upload
      v-model="uploadVisible"
      :title="uploadTitle"
      :user-person="shadowYiyaClinicPerson"
      :user-appointment="shadowYiyaAppointment"
      @change="closeHandle"
      @submit="addNewShadow"
    />
    <appointment-panel
      v-model="appointmentPanelVisible"
      :default-data="appointmentPanelData"
      :default-patient="appointmentPanelPatient"
      :types="add"
      @submit="getListAppointment"
    ></appointment-panel>
    <update-visit
      v-model="isVisitVisible"
      :patient="isVisitYiyaClinicPerson"
      :doctor-list="doctorList"
      title="新建随访"
      @ok="addIsVisits"
      @close="handleClose"
    ></update-visit>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import moment from 'moment'
import { addCase } from '@/api/erp/case'
import { mapGetters, mapState } from 'vuex'
import {
  allListAppointment,
  updateAppointment,
  listAppointment,
} from '@/api/services/appointment'
import { postName } from '@/api/system/user'
import { encode } from '@/utils/utils'
import Empty from '@/components/yiya/Empty'
import {
  ColumnsFilterButton,
  ColumnsFilterView,
} from '@/components/yiya/TableColumnsFilter'
import hoverPhone from '@/components/yiya/hoverPhone'
import market from '@/mixins/market'
import MedicalEditor from '@/views/components/TabsPanes/MedicalRecordPane/MedicalEditor'
import Upload from '@/views/components/TabsPanes/ImageRecordPane/Upload'
import { addShadows } from '@/api/erp/shadow'
import AppointmentPanel from '@/views/market/marketView/AppointmentPanel'
import updateVisit from '@/views/components/TabsPanes/FollowupVisitPane/updateVisit'
import { addDoctor } from '@/api/services/doctor'
const startTimes = '00:00:00'
const endTimes = '23:59:59'
export default {
  name: 'TCDiagnose',
  components: {
    Empty,
    ColumnsFilterButton,
    ColumnsFilterView,
    hoverPhone,
    MedicalEditor,
    Upload,
    AppointmentPanel,
    updateVisit,
  },
  mixins: [market],
  data() {
    return {
      add: '复诊预约',
      startReservationTime: undefined,
      endReservationTime: undefined,
      appointmentPanelVisible: false,
      appointmentPanelData: {},
      appointmentPanelPatient: undefined,
      uploadTitle: '上传影像',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 到店患者信息表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'reservationDate',
        isAsc: 'desc',
        clinicId: undefined,
        startOnClinicTime: undefined,
        endOnClinicTime: undefined,
      },
      params: {
        postname: '医生',
        deptId: '',
      },
      dateTimeValue: '',
      doctorList: [],
      medicalEditorVisible: false,
      uploadVisible: false,
      patientId: 0,
      titles: '新增病历',
      caseYiyaAppointment: {},
      caseYiyaClinicPerson: {},
      shadowYiyaAppointment: {},
      shadowYiyaClinicPerson: {},
      isVisitVisible: false,
      isVisitYiyaAppointment: {},
      isVisitYiyaClinicPerson: {},
      clientHeight: document.body.clientHeight - 223,
    }
  },
  computed: {
    ...mapGetters('dict', ['attendanceStatus', 'sexOptions']),
    ...mapState({
      marketParams: (state) => state.pathQurey['/doctor/diagnose'] || {},
      clinicId: (state) => state.clinic.clinicId,
    }),
    ...mapState({
      userName: (state) => state.user.name,
    }),
  },
  watch: {
    marketParams: {
      handler(newVal) {
        if (newVal.reservationDate !== undefined) {
          this.dateTimeValue = newVal.reservationDate
          this.queryParams = newVal
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getUserListAll()
  },
  methods: {
    addIsVisits() {
      this.isVisitYiyaAppointment.isVisit = 1
      updateAppointment({
        id: this.isVisitYiyaAppointment.id,
        isVisit: this.isVisitYiyaAppointment.isVisit,
      })
      this.isVisitVisible = false
    },
    handleClose() {
      this.isVisitVisible = false
    },
    handleIsVisit(rows) {
      this.isVisitVisible = true
      this.isVisitYiyaAppointment = rows.yiyaAppointment
      this.isVisitYiyaClinicPerson = rows.yiyaClinicPerson
    },
    async getListAppointment() {
      this.appointmentPanelData.isAppointment = 1
      updateAppointment({
        id: this.appointmentPanelData.id,
        isAppointment: this.appointmentPanelData.isAppointment,
      })
    },
    handleAgainAppointment(datas) {
      datas.yiyaAppointment.reservationDate = dayjs().format('YYYY-MM-DD')
      this.appointmentPanelVisible = true
      this.appointmentPanelData = datas.yiyaAppointment
      this.appointmentPanelPatient = datas.yiyaClinicPerson
    },
    closeHandle(e) {
      this.uploadVisible = e
    },
    addShadows(rows) {
      this.uploadVisible = true
      this.shadowYiyaAppointment = rows.yiyaAppointment
      this.shadowYiyaClinicPerson = rows.yiyaClinicPerson
    },
    addNewShadow(e) {
      const { url } = e
      let params = {
        yiyaResourceShadows: [],
      }
      url.forEach((item) => {
        params.yiyaResourceShadows.push({
          remarks: e.remarks,
          clinicTime: e.clinicTime,
          clinicPersonId: parseInt(this.shadowYiyaClinicPerson.id),
          createBy: this.userName,
          type: e.type,
          url: item.url,
        })
      })
      addShadows(params).then((res) => {
        if (res.code === 200) {
          this.shadowYiyaAppointment.isShadow = 1
          updateAppointment({
            id: this.shadowYiyaAppointment.id,
            isShadow: this.shadowYiyaAppointment.isShadow,
          })
          this.msgSuccess('新增成功')
        } else {
          this.msgError(res.msg)
        }
      })
    },
    addCaseHandle(rows) {
      this.medicalEditorVisible = true
      this.patientId = parseInt(rows.yiyaClinicPerson.id)
      this.caseYiyaAppointment = rows.yiyaAppointment
      this.caseYiyaClinicPerson = rows.yiyaClinicPerson
    },
    addNewCase(fromData) {
      if (fromData.title == '新增病历') {
        addCase(fromData).then((response) => {
          if (response.code === 200) {
            this.caseYiyaAppointment.isCase = 1
            updateAppointment({
              id: this.caseYiyaAppointment.id,
              isCase: this.caseYiyaAppointment.isCase,
            })
            this.msgSuccess('新增成功')
          } else {
            this.msgError(response.msg)
          }
        })
      }
    },
    changeHandle(e) {
      this.medicalEditorVisible = e
    },
    selectDoctor(e) {
      this.queryParams.doctorId = e
      this.resetRouter()
    },
    async getUserListAll() {
      this.params.deptId = this.clinicId
      const { data } = await postName(this.params)
      this.doctorList = data
    },
    goDetails(row) {
      this.$router.push(
        `/doctor/details?id=${row.yiyaClinicPerson.id}&appointmentId=${
          row.yiyaAppointment.id
        }&redirect=${encode({
          path: this.$route.path,
          query: this.queryParams,
        })}`
      )
    },
    doubleHandle(row) {
      this.goDetails(row)
    },
    handleDetails(row, column, event) {
      if (
        event.target._prevClass == 'el-radio__inner' ||
        event.target._prevClass == 'el-radio__label' ||
        event.target._prevClass == 'el-radio__input' ||
        event.target._prevClass == 'el-radio__original'
      ) {
        event.preventDefault()
        this.radio = this.list.indexOf(row)
        this.ids = [row]
        this.multiple = false
        this.selectedIndex = row.index
        this.userType = row.channelFirst
        return
      }
      if (event.target._prevClass == undefined) {
        this.goDetails(row)
      } else {
        return
      }
    },
    checkReception(data, msg) {
      console.log(data)
      this.$confirm(`确认${data.clinicPersonName}的患者${msg}吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          if (msg == '开始治疗') {
            data.appointmentStatus = 4
          } else {
            data.appointmentStatus = 5
          }
          return updateAppointment({
            id: data.id,
            appointmentStatus: data.appointmentStatus,
          })
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess(`${msg}成功`)
          }
        })
        .catch(function () {
          return
        })
    },
    /** 查询到店患者信息列表 */
    async getList() {
      this.loading = true
      this.queryParams.clinicId = this.clinicId
      await allListAppointment(this.queryParams).then((response) => {
        for (const item of response.rows) {
          item.yiyaAppointment.onClinicTimeDate = moment(
            item.yiyaAppointment.onClinicTime
          ).valueOf()
        }
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /**
     * 翻译字典
     */
    // formatterDict(value, optionsKey) {
    //   return this.selectDictLabel(this[optionsKey], value)
    // },
    /** 搜索按钮操作 */
    async handleQuery(e) {
      this.queryParams.pageNum = 1
      await this.resetRouter()
    },
    /** 重置按钮操作 */
    async resetQuery() {
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        reservationDate: this.queryParams.reservationDate,
        orderByColumn: this.queryParams.orderByColumn,
        isAsc: this.queryParams.isAsc,
      }
      this.queryParams = params
      this.$store.dispatch('pathQurey/setMarketQuery', {
        path: this.$route.path,
        data: this.queryParams,
      })
      await this.resetRouter()
    },
    async resetRouter() {
      this.$store.dispatch('pathQurey/setMarketQuery', {
        path: this.$route.path,
        data: this.queryParams,
      })
      await this.getList()
    },
    startTimeFn(date, str) {
      const startTime = this.parseTime(date, '{y}-{m}-{d}')
      return `${startTime} ${str}`
    },
    async prev() {
      this.dateTimeValue = moment(this.dateTimeValue).subtract(1, 'days')
      this.queryParams.reservationDate = this.parseTime(
        this.dateTimeValue._d,
        '{y}-{m}-{d}'
      )
      this.queryParams.startOnClinicTime = this.startTimeFn(
        this.dateTimeValue._d,
        startTimes
      )
      this.queryParams.endOnClinicTime = this.startTimeFn(
        this.dateTimeValue._d,
        endTimes
      )
      await this.resetRouter()
    },
    async next() {
      this.dateTimeValue = moment(this.dateTimeValue).add(1, 'days')
      this.queryParams.reservationDate = this.parseTime(
        this.dateTimeValue._d,
        '{y}-{m}-{d}'
      )
      this.queryParams.startOnClinicTime = this.startTimeFn(
        this.dateTimeValue._d,
        startTimes
      )
      this.queryParams.endOnClinicTime = this.startTimeFn(
        this.dateTimeValue._d,
        endTimes
      )
      await this.resetRouter()
    },
    async onChange(value) {
      this.queryParams.reservationDate = this.parseTime(value, '{y}-{m}-{d}')
      this.queryParams.startOnClinicTime = this.startTimeFn(value, startTimes)
      this.queryParams.endOnClinicTime = this.startTimeFn(value, endTimes)
      await this.resetRouter()
    },
    async changeTime(e) {
      this.dateTimeValue = this.parseTime(e[0].$d, '{y}-{m}-{d}')
      await this.changeTimeDate(e[0].$d)
    },
    async changeTimeDate(e) {
      if (Object.keys(this.marketParams).length > 2) {
        this.queryParams = this.marketParams
        console.log(1)
      } else {
        this.queryParams.reservationDate = this.parseTime(e, '{y}-{m}-{d}')
        this.queryParams.startOnClinicTime = this.startTimeFn(e, startTimes)
        this.queryParams.endOnClinicTime = this.startTimeFn(e, endTimes)
      }
      await this.resetRouter()
    },
  },
}
</script>
<style scoped>
@import '../../market/static/style.scss';
</style>

